/**
 * @author: ares
 * @date: 2020/1/30 17:15
 * @description: bodyTab
 */
layui.define(["element", "jquery", "conf", "store", "utils", "_"], function (exports) {
    var element = layui.element,
        config = layui.conf,
        store = layui.store,
        utils = layui.utils,
        lodash = layui._,
        $ = layui.$;

    /**
     * @author: ares
     * @date: 2021/3/20 8:50
     * @description: 加载spa页面
     * @param {string}url  文件地址
     * @param {function}callback
     */
    function loadView(url, callback) {
        utils.loadView(url, $('#sys-tabs-content>.layui-tab-item.layui-show'), callback)
    }

    /**
     * @author: ares
     * @date: 2021/3/20 8:51
     * @description: 加载iframe页面
     * @param {string}url  文件地址
     * @param {function}callback
     */
    function loadIframeView(url, callback) {
        utils.loadIframeView(url, $('#sys-tabs-content>.layui-tab-item.layui-show'), callback);
    }

    /**
     * @author: ares
     * @date: 2021/3/20 8:51
     * @description: 重新加载iframe还是仅调用iframe的init方法
     * @param {string}url  文件地址
     * @param {boolean}init  如果iframe已经加载过了,是否调用它的init方法重置页面数据
     * @param {function}callback
     */
    function initCurrentIframeView(url, init, callback) {
        if ($('#sys-tabs-content>.layui-tab-item.layui-show>iframe').length) {
            var contentWindow = $('#sys-tabs-content>.layui-tab-item.layui-show>iframe')[0].contentWindow;
            if (init && typeof contentWindow.init == 'function') contentWindow.init();
            return;
        }
        utils.loadIframeView(url, $('#sys-tabs-content>.layui-tab-item.layui-show'), callback);
    }

    /**
     * @author: ares
     * @date: 2021/3/20 8:55
     * @description: 生成系统tab
     * @param {string}hash
     * @param {string}icon
     * @param {string}fullFilePath
     * @param {string}title
     * @returns {string}
     */
    function getTabTitle(hash, icon, fullFilePath, title) {
        return '<a href="#' + hash + '">' +
            '<i class="tab-icon ' + icon + '"></i>' +
            '<cite class="tab-title" data-file="' + fullFilePath + '">' + title + '</cite>' +
            '</a>';
    }

    function BodyTab() {
        this.config = {
            maxOpenTabNum: 8,  //最大可打开窗口数量
            tabFilter: "bodyTab",  //添加窗口的filter
        };
        $.extend(true, this.config, config)
    };

    BodyTab.prototype = {
        constructor: BodyTab,
        /**
         * @author: ares
         * @date: 2020/1/30 11:49
         * @description: 覆盖config
         * @param {object}option
         * @returns {Tab}
         */
        set: function (option) {
            $.extend(true, this.config, option);
            return this;
        },

        /**
         * @author: ares
         * @date: 2020/1/30 11:55
         * @description: 根据tab标题获取layId
         * @param {string}title  tab标题
         * @returns {*}
         */
        getLayId: function (title) {
            var layId;
            $("#sys-tabs>li").each(function () {
                if ($(this).find(".tab-title").text() == title) {
                    layId = $(this).attr("lay-id");
                    return false;
                }
            })
            return layId;
        },

        /**
         * @author: ares
         * @date: 2020/1/30 12:01
         * @description: tabs中是否存在对应标题的tab
         * @param {string}title 标题
         * @returns {boolean}
         */
        hasTab: function (title) {
            var hasTab = false;
            $("#sys-tabs>li").each(function () {
                if ($(this).find(".tab-title").text() == title) {
                    hasTab = true;
                    return false;
                }
            })
            return hasTab;
        },

        /**
         * @author: ares
         * @date: 2020/12/26 19:20
         * @description: 添加tab
         * @param {string}title
         * @param {string}hash
         * @param {string}filePath
         * @param {string}icon
         * @param {string}refresh    refresh(刷新整个页面)|init(重新加载init方法)|false或其它参数(不做处理)
         * @param {function}callback
         * @returns {*}
         */
        addTab: function (title, hash, filePath, icon, refresh, callback) {
            if (!title || !hash || !filePath) return false;
            if (typeof icon == 'function') {
                refresh = false;
                callback = icon;
                icon = '';
            }
            if (typeof refresh == 'function') {
                callback = refresh;
                refresh = false;
            }
            var fullFilePath = filePath.split('#')[0] + '#' + hash,
                tabFilter = this.config.tabFilter,
                maxOpenTabNum = this.config.maxOpenTabNum,
                $sysTabs = $("#sys-tabs>li"),
                tabTitle = getTabTitle(hash, icon, fullFilePath, title);
            //如果对应的tab已经存在,跳转到对应的tab
            if (this.hasTab(title)) {
                var _layId = this.getLayId(title);
                element.tabChange(tabFilter, _layId);
                if (refresh == 'refresh') {
                    //重新加载整个iframe页面
                    loadIframeView(fullFilePath, callback);
                } else if (refresh == 'init') {
                    //调用iframe的init方法重置iframe页面数据
                    initCurrentIframeView(fullFilePath, true, callback);
                } else {
                    //不调用iframe页面init方法
                    initCurrentIframeView(fullFilePath, false, callback);
                }
            } else {
                //如果是新tab
                element.tabAdd(tabFilter, {
                    title: tabTitle,
                    id: hash
                })
                //跳转到新打开的tab
                element.tabChange(tabFilter, hash);
                //加载文件
                loadIframeView(fullFilePath);
                //tabs数量大于设定上限,自动关闭首位可关闭的tab
                if ($sysTabs.length > maxOpenTabNum) {
                    var deleteLayId;
                    $sysTabs.each(function () {
                        var layId = $(this).attr('lay-id');
                        if (layId != config.homePagePath) {
                            deleteLayId = layId;
                            return false;
                        }
                    })
                    element.tabDelete(tabFilter, deleteLayId)
                }
            }
            return this;
        },

        /**
         * @author: ares
         * @date: 2020/1/30 19:22
         * @description: 更新sessionStorage中的openedTabs和curTab
         */
        updateSessionStorageTab: function (index, $this, append) {
            var idx = index == 0 ? index : index - 1,
                sessionTabs = store.session.get('openedTabs') || [],
                curTab = $this && typeof $this == 'object' ? {
                    path: $this.attr('lay-id'),
                    title: $this.find(".tab-title").text(),
                    filePath: $this.find(".tab-title").data('file'),
                    icon: $this.find(".tab-icon").attr('class'),
                } : null,
                filterSessionTabs = [];
            if (append) {
                filterSessionTabs = lodash.filter(sessionTabs, function (tab) {
                    return tab.path == curTab.path;
                });
                if (curTab.path != config.homePagePath && !filterSessionTabs.length) sessionTabs.push(curTab)
            } else {
                sessionTabs.splice(idx, 1)
            }
            store.session.set('openedTabs', sessionTabs)
            curTab && store.session.set('curTab', curTab)
            return this;
        },

        /**
         * @author: ares
         * @date: 2020/12/26 22:03
         * @description: 加载缓存中的tab
         */
        loadSessionTabs: function (sessionTabs) {
            var tabFilter = this.config.tabFilter,
                curTab = store.session.get('curTab') || {},
                sessionTabs = sessionTabs || store.session.get('openedTabs');
            if (!$.isArray(sessionTabs) || !sessionTabs.length) return;
            $.each(sessionTabs, function (index, item) {
                var tabTitle = getTabTitle(item.path, item.icon, item.filePath, item.title);
                element.tabAdd(tabFilter, {
                    title: tabTitle,
                    id: item.path
                })
            })
            bodyTab.addTab(curTab.title, curTab.path, curTab.filePath, curTab.icon);
            return this;
        },

        /**
         * @author: ares
         * @date: 2020/1/30 21:51
         * @description: 刷新当前tab
         */
        refresh: function () {
            var $refreshBtn = $("#sys-tabs-wrap>.close-box .refresh"),
                filePath = $('#sys-tabs>li.layui-this').find('.tab-title').data('file');
            if ($refreshBtn.hasClass("refresh-able")) {
                $refreshBtn.removeClass("refresh-able");
                loadIframeView(filePath, function () {
                    $refreshBtn.addClass("refresh-able");
                });
            } else {
                utils.message("您的刷新频率过快，请休息片刻再次刷新！");
            }
        },

        /**
         * @author: ares
         * @date: 2020/1/30 21:54
         * @description: 关闭其它tab
         */
        closeOtherTab: function () {
            var that = this,
                $sysTabs = $("#sys-tabs>li");
            if ($sysTabs.length) {
                $sysTabs.each(function () {
                    var layId = $(this).attr("lay-id");
                    if (!$(this).hasClass("layui-this") && layId != config.homePagePath) element.tabDelete(that.config.tabFilter, layId).render();
                })
            } else {
                utils.message("没有可以关闭的窗口了@_@");
            }
        },

        /**
         * @author: ares
         * @date: 2020/1/31 9:44
         * @description: 关闭所有tab
         */
        closeAllTab: function () {
            var that = this,
                $sysTabs = $("#sys-tabs>li");
            if ($sysTabs.length) {
                $sysTabs.each(function () {
                    var layId = $(this).attr("lay-id");
                    if (layId != config.homePagePath) element.tabDelete(that.config.tabFilter, layId).render();
                })
            } else {
                utils.message("没有可以关闭的窗口了@_@");
            }
        },
    };

    var bodyTab = new BodyTab();

    /**
     * @author: ares
     * @date: 2020/1/30 17:49
     * @description: 监听tab切换,更新sessionStorage中的当前tab
     */
    element.on('tab(' + bodyTab.config.tabFilter + ')', function (data) {
        utils.highLightAside();
        utils.updateBreadcrumb(top.layui.routers);
        bodyTab.updateSessionStorageTab(data.index, $(this), true);
    })

    /**
     * @author: ares
     * @date: 2020/1/30 19:22
     * @description: 监听tab删除
     */
    element.on('tabDelete(' + bodyTab.config.tabFilter + ')', function (data) {
        utils.replaceRoute($(data.elem).find('#sys-tabs>li.layui-this').attr('lay-id') || config.homePagePath)
        bodyTab.updateSessionStorageTab(data.index, null, false);
    })

    /**
     * @author: ares
     * @date: 2020/1/30 19:36
     * @description: 刷新当前tab
     */
    $("#sys-tabs-wrap>.close-box .refresh").on("click", function () {
        bodyTab.refresh()
    })

    /**
     * @author: ares
     * @date: 2020/1/31 9:42
     * @description: 关闭其它可关闭且非当前tab
     */
    $("#sys-tabs-wrap>.close-box .close-page-other").on("click", function () {
        bodyTab.closeOtherTab()
    })

    /**
     * @author: ares
     * @date: 2020/1/31 9:45
     * @description: 关闭所有可关闭的tab
     */
    $("#sys-tabs-wrap>.close-box .close-page-all").on("click", function () {
        bodyTab.closeAllTab()
    })

    exports("bodyTab", bodyTab);
})
